package com.logistic.server.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.logistic.server.common.constant.Constants;
import com.logistic.server.common.exception.BaseException;
import com.logistic.server.entity.common.PageRequest;
import com.logistic.server.entity.common.PageResponse;
import com.logistic.server.entity.pojo.SysPost;
import com.logistic.server.entity.pojo.SysUserPost;
import com.logistic.server.mapper.SysPostMapper;
import com.logistic.server.mapper.SysUserPostMapper;
import com.logistic.server.service.ISysPostService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * 岗位信息 服务层处理
 *
 * @author swen
 */
@Service
@Transactional
public class SysPostServiceImpl extends ServiceImpl<SysPostMapper, SysPost> implements ISysPostService {

    @Resource
    private SysUserPostMapper userPostMapper;

    /**
     * 分页查询
     * @param post 参数
     * @param pageRequest 分页参数
     * @return list
     */
    @Override
    public PageResponse<SysPost> selectPagePostList(SysPost post, PageRequest pageRequest) {
        LambdaQueryWrapper<SysPost> queryWrapper = new LambdaQueryWrapper<SysPost>()
                .like(StrUtil.isNotBlank(post.getPostCode()), SysPost::getPostCode, post.getPostCode())
                .eq(StrUtil.isNotBlank(post.getStatus()), SysPost::getStatus, post.getStatus())
                .like(StrUtil.isNotBlank(post.getPostName()), SysPost::getPostName, post.getPostName());
        IPage<SysPost> page = new Page<SysPost>(pageRequest.getPageIndex(), pageRequest.getPageSize());
        IPage<SysPost> result = baseMapper.selectPage(page, queryWrapper);
        return PageResponse.<SysPost>builder().list(result.getRecords()).total(result.getTotal()).build();
    }

    /**
     * 查询岗位信息集合
     *
     * @param post 岗位信息
     * @return 岗位信息集合
     */
    @Override
    public List<SysPost> selectPostList(SysPost post) {
        return list(new LambdaQueryWrapper<SysPost>()
                .like(StrUtil.isNotBlank(post.getPostCode()), SysPost::getPostCode, post.getPostCode())
                .eq(StrUtil.isNotBlank(post.getStatus()), SysPost::getStatus, post.getStatus())
                .like(StrUtil.isNotBlank(post.getPostName()), SysPost::getPostName, post.getPostName()));
    }

    /**
     * 查询所有岗位
     *
     * @return 岗位列表
     */
    @Override
    public List<SysPost> selectPostAll() {
        return list();
    }

    /**
     * 通过岗位ID查询岗位信息
     *
     * @param postId 岗位ID
     * @return 角色对象信息
     */
    @Override
    public SysPost selectPostById(Long postId) {
        return getById(postId);
    }

    /**
     * 根据用户ID获取岗位选择框列表
     *
     * @param userId 用户ID
     * @return 选中岗位ID列表
     */
    @Override
    public List<Integer> selectPostListByUserId(Long userId) {
        return baseMapper.selectPostListByUserId(userId);
    }

    /**
     * 校验岗位名称是否唯一
     *
     * @param post 岗位信息
     * @return 结果
     */
    @Override
    public String checkPostNameUnique(SysPost post) {
        long postId = ObjectUtil.isNull(post.getPostId()) ? -1L : post.getPostId();
        SysPost info = getOne(new LambdaQueryWrapper<SysPost>()
                .eq(SysPost::getPostName, post.getPostName()).last("limit 1"));
        if (ObjectUtil.isNotEmpty(info) && info.getPostId() != postId) {
            return Constants.NOT_UNIQUE;
        }
        return Constants.UNIQUE;
    }

    /**
     * 校验岗位编码是否唯一
     *
     * @param post 岗位信息
     * @return 结果
     */
    @Override
    public String checkPostCodeUnique(SysPost post) {
        long postId = ObjectUtil.isNull(post.getPostId()) ? -1L : post.getPostId();
        SysPost info = getOne(new LambdaQueryWrapper<SysPost>()
                .eq(SysPost::getPostCode, post.getPostCode()).last("limit 1"));
        if (ObjectUtil.isNotNull(info) && info.getPostId() != postId) {
            return Constants.NOT_UNIQUE;
        }
        return Constants.UNIQUE;
    }

    /**
     * 通过岗位ID查询岗位使用数量
     *
     * @param postId 岗位ID
     * @return 结果
     */
    @Override
    public long countUserPostById(Long postId) {
        return userPostMapper.selectCount(new LambdaQueryWrapper<SysUserPost>().eq(SysUserPost::getPostId, postId));
    }

    /**
     * 删除岗位信息
     *
     * @param postId 岗位ID
     * @return 结果
     */
    @Override
    public int deletePostById(Long postId) {
        return baseMapper.deleteById(postId);
    }

    /**
     * 批量删除岗位信息
     *
     * @param postIds 需要删除的岗位ID
     */
    @Override
    public void deletePostByIds(Long[] postIds) {
        for (Long postId : postIds) {
            SysPost post = selectPostById(postId);
            if (countUserPostById(postId) > 0) {
                throw new BaseException(String.format("%1$s已分配,不能删除", post.getPostName()));
            }
        }
        baseMapper.deleteBatchIds(Arrays.asList(postIds));
    }

    /**
     * 新增保存岗位信息
     * @param post 岗位信息
     */
    @Override
    public void insertPost(SysPost post) {
        if (Constants.NOT_UNIQUE.equals(this.checkPostNameUnique(post))) {
            throw new BaseException("新增岗位'" + post.getPostName() + "'失败，岗位名称已存在");
        } else if (Constants.NOT_UNIQUE.equals(this.checkPostCodeUnique(post))) {
            throw new BaseException("新增岗位'" + post.getPostName() + "'失败，岗位编码已存在");
        }
        baseMapper.insert(post);
    }

    /**
     * 修改保存岗位信息
     * @param post 岗位信息
     */
    @Override
    public void updatePost(SysPost post) {
        if (Constants.NOT_UNIQUE.equals(this.checkPostNameUnique(post))) {
            throw new BaseException("修改岗位'" + post.getPostName() + "'失败，岗位名称已存在");
        } else if (Constants.NOT_UNIQUE.equals(this.checkPostCodeUnique(post))) {
            throw new BaseException("修改岗位'" + post.getPostName() + "'失败，岗位编码已存在");
        }
        baseMapper.updateById(post);
    }
}
